package jwt

import (
	"context"
	"errors"
	"fmt"
	"strings"

	"go-zero_try/mall/order/api/internal/svc"
	"go-zero_try/mall/order/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type DecodeJwtLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDecodeJwtLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DecodeJwtLogic {
	return &DecodeJwtLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *DecodeJwtLogic) DecodeJwt() (resp *types.JwtReps, err error) {
	id := fmt.Sprintf("%v", l.ctx.Value("userId"))

	exists, err := l.svcCtx.Redis.Exists("loginUserId:" + id).Result()

	if err != nil {
		return nil, err
	}
	if exists != 1 {
		return nil, errors.New("会话过期")
	}
	result, err := l.svcCtx.Redis.Get("loginUserId:" + id).Result()

	if err != nil {
		return nil, err
	}
	split := strings.Split(result, ";")
	return &types.JwtReps{
		Msg: "解析成功",
		Token: map[string]interface{}{
			"UID":      id,
			"Username": split[0],
			"Age":      split[1],
		},
	}, nil
}
